package fun.boomcat.luckyhe.mirai.plugin.luckymoney.util;

import fun.boomcat.luckyhe.mirai.plugin.luckymoney.mapper.MoneyMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Map;

/**
 * @author Lucky_He
 * @date 2021年9月5日 14:15
 * @description MyBatisUtil
 */
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSession getSqlSession() throws IOException {
        if (sqlSessionFactory == null) {
            String driver = "com.mysql.jdbc.Driver";

            Map<String, String> connMap;

            connMap = ConfigUtil.getMySqlConnInfo();

            String url = connMap.get("url");
            String username = connMap.get("username");
            String password = connMap.get("password");

            DataSource dataSource = getDataSource(driver, url, username, password);
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("development", transactionFactory, dataSource);
            Configuration configuration = new Configuration(environment);

            configuration.addMapper(MoneyMapper.class);

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        }
        return sqlSessionFactory.openSession();
    }

    private static DataSource getDataSource(String driver, String url, String username, String password) {
        PooledDataSource dataSource = new PooledDataSource();

        dataSource.setDriver(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }
}
